package com.c2rusthub.service.controller;

import com.c2rusthub.service.model.User;
import com.c2rusthub.service.request.LoginRequest;
import com.c2rusthub.service.response.Response;
import com.c2rusthub.service.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/decoding-ark")
public class UserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    // 获取所有用户的接口
    @GetMapping("/users")
    public ResponseEntity<Response> getUsers() {

        return success(userService.getAllUsers());
    }

    /**
     * 用户登录
     *
     * @param loginRequest 登录参数
     * @return ResponseEntity<Response>
     * @author zhaozhiju
     * @date 2024/12/2 2:25 PM
     */
    @PostMapping("/user/log-in")
    public ResponseEntity<Response> logIn(@RequestBody LoginRequest loginRequest) {
        logger.info("####### 用户登录，loginRequest=[{}] #######", loginRequest.getAccount());

        // 调用服务层处理登录逻辑
        User user = userService.logIn(loginRequest.getAccount(), loginRequest.getPassword());

        if (user == null) {
            logger.error("####### 用户名或密码错误 #######");
            return failure("用户名或密码错误");
        }

        return success(user);
    }

    /**
     * 退出登录
     *
     * @param request request
     * @return ResponseEntity<Response>
     * @author zhaozhiju
     * @date 2024/12/2 2:33 PM
     */
    @PostMapping("/user/log-out")
    public ResponseEntity<Response> logOut(HttpServletRequest request) {
        User userFromToken = getUserFromToken(request);
        logger.info("####### 用户退出登录，userName=[{}] #######", userFromToken.getName());
        userService.logOut(userFromToken.getToken());
        return success();
    }
}
